layui.use(['layer', 'table', 'admin', 'ax', 'func', 'form', 'layer', 'upload'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var func = layui.func;
    var form = layui.form;
    var layer = layui.layer;
    var upload = layui.upload;

    /**
     * 客户管理
     */
    var Client = {
        tableId: "clientTable"
    };

    /**
     * 初始化表格的列
     */
    Client.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: ''},
            {field: 'clientCode', sort: true, title: '客户代码', width: 110},
            {field: 'clientName', sort: true, title: '客户名称', width: 110},
            {field: 'phone', sort: true, title: '固定电话', width: 130},
            {field: 'mobile', sort: true, title: '手机号码', width: 120},
            {field: 'linkMan', sort: true, title: '联系人'},
            {field: 'address', sort: true, title: '登记地址', width: 150},
            {field: 'contactTax', sort: true, title: '税率'},
            {
                field: 'audit', sort: true, title: '审核', templet: function (d) {
                    if (d.audit == 0) {
                        return '<span class="layui-badge layui-badge">未审</span>';
                    }
                    return '<span class="layui-badge layui-bg-green">已审</span>';
                }
            },
            {field: 'outerCode', sort: true, title: '外部编码', width: 110},
            {field: 'discount', sort: true, title: '折扣'},
            {
                field: 'state', sort: true, title: '停用', templet: function (d) {
                    var checked = '';
                    if (d.state == 1) {
                        checked = 'checked';
                    }
                    return '<input type="checkbox" name="state" data-id="' + d.id + '" lay-skin="switch" lay-filter="state" lay-text="是|否" ' + checked + '>';
                }
            },
            {field: 'createTime', sort: true, title: '创建时间', width: 160},
            {field: 'updateTime', sort: true, title: '更新时间', width: 160},
            {field: 'remark', sort: true, title: '备注'},
            {align: 'center', toolbar: '#tableBar', title: '操作', width: 120, fixed: 'right'}
        ]];
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Client.tableId,
        url: Changein.ctxPath + '/client/list',
        page: true,
        height: "full-130",
        cellMinWidth: 100,
        cols: Client.initColumn()
    });

    //表格中的启用/禁用
    form.on('switch(state)', function (data) {
        var val = data.elem.checked ? 1 : 0;
        var id = data.elem.getAttribute("data-id");
        var ajax = new $ax(Changein.ctxPath + "/client/setState", function (data) {
            Changein.success("修改成功！");
        }, function (data) {
            Changein.error("修改失败！" + data.responseJSON.message)
        });
        ajax.set({"ids": id, "state": val});
        ajax.start();
    });

    /**
     * 点击查询按钮
     */
    Client.search = function () {
        var queryData = {};
        queryData['clientName'] = $('#clientName').val();
        queryData['phone'] = $('#phone').val();
        queryData['mobile'] = $('#mobile').val();
        queryData['linkMan'] = $('#linkMan').val();
        queryData['audit'] = $('#audit').val();
        table.reload(Client.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 弹出添加对话框
     */
    Client.openAddDlg = function () {
        func.open({
            title: '添加客户',
            content: Changein.ctxPath + '/client/add',
            tableId: Client.tableId
        });
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Client.openEditDlg = function (data) {
        func.open({
            title: '修改客户',
            content: Changein.ctxPath + '/client/edit?id=' + data.id,
            tableId: Client.tableId
        });
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    Client.onDeleteItem = function (data) {
        let audit = data.audit;
        if (audit == 1) {
            Changein.error("选择的数据已审核");
            return false;
        }
        var operation = function () {
            var ajax = new $ax(Changein.ctxPath + "/client/delete", function (data) {
                if (data.code == 200) {
                    Changein.success("删除成功!");
                    table.reload(Client.tableId);
                } else {
                    Changein.error("删除失败!" + data.message + "!");
                }
            }, function (data) {
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set({"id": data.id, "audit": audit});
            ajax.start();
        };
        Changein.confirm("是否删除?", operation);
    };

    /**
     * 批量删除
     */
    var deleteLock = false;
    Client.deleteBatch = function () {
        if (!deleteLock) {
            deleteLock = true;
            var checkRows = table.checkStatus(Client.tableId);
            if (checkRows.data.length == 0) {
                deleteLock = false;
                Changein.error("请选择要删除的数据");
                return false;
            }
            var arr = [];
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit != 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                deleteLock = false;
                Changein.error("选中数据全部已审核，请选择未审核的数据");
                return false;
            }
            var operation = function () {
                var ajax = new $ax(Changein.ctxPath + "/client/deleteList", function (data) {
                    if (data.code == 200) {
                        deleteLock = false;
                        Changein.success("批量删除成功！");
                        table.reload(Client.tableId);
                    } else {
                        deleteLock = false;
                        Changein.error("批量删除失败！" + data.message)
                    }
                }, function (data) {
                    deleteLock = false;
                    Changein.error("批量删除失败！" + data.responseJSON.message)
                });
                ajax.set({"ids": arr.toString()});
                ajax.start();
            };
            deleteLock = false;
            Changein.confirm("是否删除", operation)
        } else {
            Changein.error("正在删除中");
        }
    };

    /**
     * 启用/禁用
     */
    var enableLock = false;
    Client.enable = function () {
        if (!enableLock) {
            enableLock = true;
            var checkRows = table.checkStatus(Client.tableId);
            if (checkRows.data.length === 0) {
                enableLock = false;
                Changein.error("请选择要启用/禁用的数据");
                return false;
            }
            var arr = [];
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].id) {
                    arr.push(tabData[i].id);
                }
            }
            var operation = function () {
                var ajax = new $ax(Changein.ctxPath + "/client/setState", function (data) {
                    enableLock = false;
                    Changein.success("启用/禁用成功！");
                    table.reload(Client.tableId);
                }, function (data) {
                    enableLock = false;
                    Changein.error("启用/禁用失败！" + data.responseJSON.message)
                });
                ajax.set({"ids": arr.toString()});
                ajax.start();
            };
            enableLock = false;
            Changein.confirm("是否启用/禁用", operation)
        } else {
            Changein.error("正在启用/禁用中");
        }
    };

    /**
     * 审核
     */
    var auditLock = false;
    Client.audit = function () {
        if (!auditLock) {
            auditLock = true;
            var arr = [];
            var checkRows = table.checkStatus(Client.tableId);
            if (checkRows.data.length == 0) {
                auditLock = false;
                Changein.error("请选择要审核的数据");
                return false;
            }
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit != 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                auditLock = false;
                Changein.error("选中数据全部已审核");
                return false;
            }
            var operation = function () {
                var ajax = new $ax(Changein.ctxPath + "/client/setAudit", function (data) {
                    auditLock = false;
                    Changein.success("审核成功！");
                    table.reload(Client.tableId);
                }, function (data) {
                    auditLock = false;
                    Changein.error("审核失败！" + data.responseJSON.message)
                });
                ajax.set({"ids": arr.toString(), "audit": 1});
                ajax.start();
            };
            auditLock = false;
            Changein.confirm("是否审核", operation)
        } else {
            Changein.error("正在审核中");
        }
    };

    /**
     * 反审核
     */
    var unAuditLock = false;
    Client.unAudit = function () {
        if (!unAuditLock) {
            unAuditLock = true;
            var arr = [];
            var checkRows = table.checkStatus(Client.tableId);
            if (checkRows.data.length == 0) {
                unAuditLock = false;
                Changein.error("请选择要反审核的数据");
                return false;
            }
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit == 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                unAuditLock = false;
                Changein.error("选中数据全部未审核");
                return false;
            }
            var operation = function () {
                var ajax = new $ax(Changein.ctxPath + "/client/setAudit", function (data) {
                    unAuditLock = false;
                    Changein.success("反审核成功！");
                    table.reload(Client.tableId);
                }, function (data) {
                    unAuditLock = false;
                    Changein.error("反审核失败！" + data.responseJSON.message)
                });
                ajax.set({"ids": arr.toString(), "audit": 0});
                ajax.start();
            };
            unAuditLock = false;
            Changein.confirm("是否反审核", operation)
        } else {
            Changein.error("正在反审核中");
        }
    };


    //下载模板
    $("#btnDownloadTemplate").click(function () {
        Changein.downLoadTempate("CLIENT_IMPORT_TEMPLATE");
    });

    //导入
    $("#btnImport").click(function () {
        Client.importExcel();
    });

    //导入
    var importLock = false;
    Client.importExcel = function () {
        if (!importLock) {
            Changein.confirm("是否导入?", function () {
                setTimeout(function () {
                    $("#uploadBtn").click();
                }, 10)
            });
        } else {
            Changein.error("正在导入中");
        }
    };

    upload.render({
        elem: '#uploadBtn' //绑定元素
        , url: '/client/importExcel' //上传接口
        , accept: 'file'
        , exts: 'xlsx|xls',
        choose: function (obj) {
            importLock = true;
        }
        , done: function (res) {
            //上传完毕回调
            importLock = false;
            if (res.code != 200) {
                Changein.errorHtml('导入失败', res.message);
            } else {
                Changein.success("导入成功！");
                table.reload(Client.tableId);
            }
        }
        , error: function () {
            //请求异常回调
            importLock = false;
            Changein.error("网络异常");
        }
    });


    /**
     * 导出excel按钮，并控制点击次数
     */
    var exportExcelLock = false;
    Client.exportExcel = function () {
        if (!exportExcelLock) {
            var operation = function () {
                exportExcelLock = true;
                var params = '';
                var checkRows = table.checkStatus(Client.tableId);
                if (checkRows.data.length === 0) {
                    Changein.info("导出成功！");
                    let clientName = $('#clientName').val();
                    let phone = $('#phone').val();
                    let mobile = $('#mobile').val();
                    let linkMan = $('#linkMan').val();
                    let audit = $('#audit').val();
                    params = 'clientName=' + clientName + '&phone=' + phone + "&mobile=" + mobile + "&linkMan=" + linkMan + "&audit=" + audit;
                } else {
                    Changein.info("已选中数据，正在导出中");
                    var tabData = checkRows.data;
                    var arr = [];
                    for (var i = 0; i < tabData.length; i++) {
                        arr.push(tabData[i].id);
                    }
                    params = 'ids=' + arr.toString();
                }
                window.location.href = Changein.ctxPath + "/client/exportExcel?" + params;
                setTimeout(function () {
                    exportExcelLock = false;
                }, 5000);
            }
            Changein.confirm("是否导出?", operation);
        } else {
            Changein.error("正在导出中");
        }
    };

    // 搜索按钮点击事件
    $('#btnSearch').click('keydown', function (event) {
        Client.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Client.openAddDlg();
    });

    // 批量删除
    $("#btnDel").click(function () {
        Client.deleteBatch();
    });

    //启用/禁用
    $("#btnEnable").click(function () {
        Client.enable();
    });

    //审核
    $('#btnAudit').click(function () {
        Client.audit();
    });

    //反审核
    $('#btnUnAudit').click(function () {
        Client.unAudit();
    });

    //导入
    $("#btnImport").click(function () {
        Client.importExcel();
    });

    // 导出excel
    $('#btnExp').click(function () {
        var tableLen =  table.cache.clientTable.length;
        if (tableLen == 0){
            Changein.error("当前暂无数据");
            return false;
        }
        Client.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + Client.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            Client.openEditDlg(data);
        } else if (layEvent === 'delete') {
            Client.onDeleteItem(data);
        }
    });

});
